package com.watchmen.mini.common.config;

import com.watchmen.mini.common.utils.RedisUtil;
import com.watchmen.mini.common.utils.Result;
import com.watchmen.mini.modules.sys.entity.User;
import com.watchmen.mini.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Title: RestControllerResponseAdvice
 * @Description:
 * @Author Gapenne
 * @Version 2019/12/30 11:51
 */

@RestControllerAdvice
public class RestControllerResponseAdvice implements ResponseBodyAdvice<Object> {

    @Autowired
    private RedisUtil redisUtil;

    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    public Object beforeBodyWrite(Object obj, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        User user = UserUtils.getUser();
        if(user != null && obj != null){
            try{
                Result result = (Result) obj;
                String device = getDevice(request);
                Long time = redisUtil.getExpire(device+"_"+user.getLoginName());
                if(time != null){
                    result.setExpire(time);
                }else{
                    result.setExpire(0l);
                }
                return result;
            }catch (ClassCastException ex){
                return obj;
            }
        }
        return obj;
    }

    //设备标识
    public static String getDevice(ServerHttpRequest request){
        String userAgent = request.getHeaders().get("user-agent").toString().toLowerCase();
        if(userAgent.indexOf("android") != -1){
            return "mobile";
        }else if(userAgent.indexOf("iphone") != -1 || userAgent.indexOf("ipad") != -1 || userAgent.indexOf("ipod") != -1){
            return "mobile";
        }else{
            return "pc";
        }
    }


}


